package com.mg.framework.kernel;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

public abstract class FramesActor extends BaseActor {

	protected volatile int width = 0;
	protected volatile int height = 0;
	protected Bitmap[] bitmaps = null;
	protected int currentFrame = 0;
	protected Screen screen = null;

	public FramesActor(Screen screen, Bitmap[] bitmaps) {
		super();
		this.bitmaps = bitmaps;
		initActor(screen);
	}

	public FramesActor(Screen screen, Bitmap bitmap, int pathWidth,
			int pathHeight) {
		super();
		int xCount = bitmap.getHeight() / pathHeight;
		int yCount = bitmap.getWidth() / pathWidth;
		int number = 0;
		this.bitmaps = new Bitmap[xCount * yCount];
		for (int i = 0; i < xCount; i++) {
			for (int j = 0; j < yCount; j++) {
				this.bitmaps[number++] = Bitmap.createBitmap(bitmap, j
						* pathWidth, i * pathHeight, pathWidth, pathHeight);
			}
		}
		initActor(screen);
	}

	private void initActor(Screen screen) {
		this.width = this.bitmaps[0].getWidth();
		this.height = this.bitmaps[0].getHeight();
		this.screen = screen;
	}

	protected void drawSomeFrame(Canvas canvas, int[] frames, Paint newPaint) {
		super.drawSelf();
		if (newPaint == null) {
			canvas.drawBitmap(this.bitmaps[frames[this.currentFrame]],
					this.matrix, this.paint);
		} else {
			canvas.drawBitmap(this.bitmaps[frames[this.currentFrame]],
					this.matrix, newPaint);
		}
		if (++this.currentFrame == frames.length) {
			this.currentFrame = 0;
		}
	}

	protected void drawSelf(Canvas canvas, Paint newPaint) {
		super.drawSelf();
		if (newPaint == null) {
			canvas.drawBitmap(this.bitmaps[this.currentFrame], this.matrix,
					this.paint);
		} else {
			canvas.drawBitmap(this.bitmaps[this.currentFrame], this.matrix,
					newPaint);
		}
		if (++this.currentFrame == this.bitmaps.length) {
			this.currentFrame = 0;
		}
	}

	protected void flipHorizontally() {
		this.bitmaps = this.getNewFlipHorizontallyBitmap();
	}

	protected void flipVertically() {
		this.bitmaps = this.getNewFlipVerticallyBitmap();
	}

	private Bitmap[] getNewFlipHorizontallyBitmap() {
		Matrix matrix = flipHorizontally(this.width, this.height);
		Bitmap[] newBitmaps = new Bitmap[this.bitmaps.length];
		for (int i = 0; i < this.bitmaps.length; i++) {
			newBitmaps[i] = Bitmap.createBitmap(this.bitmaps[i], 0, 0,
					this.width, this.height, matrix, true);
		}
		return newBitmaps;
	}

	private Bitmap[] getNewFlipVerticallyBitmap() {
		Matrix matrix = flipVertically(this.width, this.height);
		Bitmap[] newBitmaps = new Bitmap[this.bitmaps.length];
		for (int i = 0; i < this.bitmaps.length; i++) {
			newBitmaps[i] = Bitmap.createBitmap(this.bitmaps[i], 0, 0,
					this.width, this.height, matrix, true);
		}
		return newBitmaps;
	}
}
